<template>
  <div class="resource-view">
    <el-dialog
      title="文件预览"
      :visible.sync="visible"
      :before-close="doCancel"
    >
      <div v-if="isVideo">
        <div v-if="loading"></div>
        <div v-else>
          <video-player ref="player" :source="signedURL"/>
        </div>
      </div>
      <div v-if="isImage">
        <img :src="signedURL"/>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import ResourceApi from "@/api/manage/resource";
  import VideoPlayer from "../player/VideoPlayer";

  export default {
	components: {
	  VideoPlayer
	},
	name: "resource-view",
	data() {
	  return {
		loading: true,
		signedURL: ""
	  };
	},
	props: {
	  visible: {
		type: Boolean,
		default: false
	  },
	  resource: {
		type: Object,
		default: null
	  }
	},
	watch: {
	  visible: function () {
		if (this.visible && this.resource != null) {
		  this.load();
		} else if (!this.visible && this.$refs.player) {
		  const player = this.$refs.player.instance;
		  player && player.pause();
		}
	  }
	},
	computed: {
	  isVideo: function () {
		return (
		  this.resource != null &&
		  (this.resource.type == "audio/mpeg" ||
			this.resource.type == "video/mp4")
		);
	  },
	  isImage: function () {
		return (
		  this.resource != null &&
		  (this.resource.type == "image/jpeg" ||
			this.resource.type == "image/png")
		);
	  }
	},
	methods: {
	  load: function () {
		this.loading = true;
		ResourceApi.view(this.resource.id).then(res => {
		  this.signedURL = res.obj.signedUrl;
		  this.loading = false;
		});
	  },
	  doCancel: function () {
		this.$emit("update:visible", false);
	  }
	}
  };
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  @require "../../common/stylus/variable.styl"
  .resource-view {
    img {
      max-width: 100%;
    }
  }
</style>
